package com.lolc.utils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import com.lolc.LoLAutoCounterManager;
import com.lolc.bean.Champion;
import com.lolc.bean.Lane;
import com.lolc.bean.Pick;


public class HTMLParser {

	private Document doc;

	private String url;

	private boolean isLocal=false;

	public HTMLParser(String url) throws IOException {
		super();
		this.url = url;

		parseHTMLDocument();
	}

	public HTMLParser(String url, boolean isLocal) throws IOException {
		super();
		this.url = url;
		this.isLocal=isLocal;

		parseHTMLDocument();
	}

	public void parseHTMLDocument() throws IOException
	{
		if(isLocal)
		{
			this.doc = Jsoup.parse(new File(this.url), "UTF-8");
		}
		else
		{
			if(Constant.HTTP_PROXY_HOST!=null && Constant.HTTP_PROXY_PORT!=null)
			{
				Properties systemProperties = System.getProperties();
				systemProperties.setProperty("http.proxyHost", Constant.HTTP_PROXY_HOST);
				systemProperties.setProperty("http.proxyPort", Constant.HTTP_PROXY_PORT);
			}

			this.doc = Jsoup.connect(this.url).timeout(0).get();
		}
	}

	public List<Champion> loadChampions()
	{
		List<Champion> list = new ArrayList<Champion>();
		//Champion list
		Elements scripts = doc.select("script");

		boolean found=false;
		for(Element elt : scripts)
		{
			List<Node> childs = elt.childNodes();
			for(Node child : childs)
			{
				if(child.nodeName().equals("#data"))
				{
					String source = child.toString();
					//LoLAutoCounterManager.getLogger().info(source);
					int i = 0;
					String beforeList="champList = [";
					String afterList="];";

					if(source.indexOf(beforeList)>-1)
					{
						int startPostion=source.indexOf(beforeList, 0);
						int endPosition=source.indexOf(afterList, startPostion);

						String champList=source.substring(startPostion+beforeList.length(),
								endPosition);

						String before="{";
						String after="}";
						int beforeSize = before.length();

						String beforeName = "\"name\":\"";
						String beforeId = "\",\"id\":\"";
						String afterId = "\",\"champ_image\"";
						int beforeNameSize = beforeName.length();
						int beforeIdSize = beforeId.length();

						while (champList.indexOf(before, i) != -1) {

							int a = champList.indexOf(before, i);
							String champion=  champList.substring(a + beforeSize,
									champList.indexOf(after, a));

							//LoLAutoCounterManager.getLogger().info(champion);
							String name =null;
							if(champion.indexOf(beforeName, 0) != -1)
							{
								name = champion.substring(champion.indexOf(beforeName, 0) + beforeNameSize,
										champion.indexOf(beforeId, 0));            
							}

							String id =null;
							if(champion.indexOf(beforeId, 0) != -1)
							{
								id = champion.substring(champion.indexOf(beforeId, 0) + beforeIdSize,
										champion.indexOf(afterId, 0));            
							}

							Champion c = new Champion(id,name);
							list.add(c);

							i = a + beforeSize;
						}     
						found=true;
					}
				}
			}

			if(found)
				break;
		}
		return list;
	}

	public void updateSynergieCounter(Champion champion) throws IOException
	{
		//Get lanes
		LoLAutoCounterManager.getLogger().info("Get lane of "+champion.getName());
		List<Lane> lanes = new ArrayList<Lane>();
		Elements divLane = this.doc.select("div.champinfo_tag");
		for(Element div:divLane)
		{			
			Elements span = div.select("span.tag_jungler");
			if(!span.isEmpty())
			{
				Lane l=new Lane("jungler");
				//Get counters
				LoLAutoCounterManager.getLogger().info("Get counter for lane 'Jungle' of "+champion.getName());
				l.setCounters(getCounters("Jungle",false));
				lanes.add(l);
			}

			span = div.select("span.tag_top");
			if(!span.isEmpty())
			{
				Lane l=new Lane("top");
				//Get counters
				LoLAutoCounterManager.getLogger().info("Get counter for lane 'Top' of "+champion.getName());
				l.setCounters(getCounters("Top",false));
				lanes.add(l);
			}

			span = div.select("span.tag_mid");
			if(!span.isEmpty())
			{
				Lane l=new Lane("mid");
				//Get counters
				LoLAutoCounterManager.getLogger().info("Get counter for lane 'Mid' of "+champion.getName());
				l.setCounters(getCounters("Mid",false));
				lanes.add(l);
			}

			span = div.select("span.tag_bottom");
			if(!span.isEmpty())
			{
				Lane l=new Lane("bottom");
				//Get counters
				LoLAutoCounterManager.getLogger().info("Get counter for lane 'Bottom' of "+champion.getName());
				l.setCounters(getCounters("Bottom",false));
				lanes.add(l);
			}
		}
		champion.setLanes(lanes);

		//Get synergie
		LoLAutoCounterManager.getLogger().info("Get synergie of "+champion.getName());
		/*List<Synergie> ls = new ArrayList<Synergie>();		
		Elements div = this.doc.select("div#duopicks-list");
		Elements href =  div.select("a[href].picks-panel-link");
		for(Element elt : href)
		{
			//LoLAutoCounterManager.getLogger().info(elt.attr("href"));
			String name = elt.attr("href");

			//Select div element placed after "a" element 
			//Element divInter = div.select("a[href="+name+"].picks-panel-link + div.picks-panel-interaction").first();
			Element divInter = elt.nextElementSibling();
			Element green = divInter.select("a.green").first();
			Element red = divInter.select("a.red").first();

			Float fgreenValue=0.0f;
			Float fredValue=0.0f;
			if(green!=null)
				fgreenValue=Float.valueOf(green.text());
			if(red!=null)
				fredValue=Float.valueOf(red.text());

			Float ratio=0.0f;
			if(fredValue>0)
			{
				ratio=fgreenValue/fredValue;
			}

			LoLAutoCounterManager.getLogger().info("->"+name+" : green="+fgreenValue+" ,red="+fredValue+" ,ratio="+ratio);
			Synergie s = new Synergie(new Champion(
					name),ratio);
			ls.add(s);
		}*/
		champion.setSynergies(getSynergie());		

		//Counters
		//Get general page
		LoLAutoCounterManager.getLogger().info("Get counters of "+champion.getName());		
		champion.setCounters(getCounters("General",true));		
	}

	/**
	 * @return the url
	 */
	public String getUrl() {
		return url;
	}

	/**
	 * @param url the url to set
	 */
	public void setUrl(String url) {
		this.url = url;
	}

	/**
	 * Get url of tab for the given lane
	 * @param id
	 * @return
	 */
	private String getUrlTabPane(String id)
	{
		Element a = doc.select("a[href=#"+id).first();
		String ajaxRequest=a.attr("onClick");
		Pattern generalPattern  = Pattern.compile("ajaxLaneCounters\\('([0-9]*)', ([0-9]*)(.*?)");
		Matcher matcher1 = generalPattern.matcher(ajaxRequest);
		String newUrl=null;
		if(matcher1.find())
		{
			String champId = matcher1.group(1);
			String laneId = matcher1.group(2);

			newUrl=url+"/../../ajax/"+champId+"/lane/"+laneId;
		}

		return newUrl;
	}

	private List<Pick> getSynergie()
	{
		List<Pick> lc = new ArrayList<Pick>();
		lc=getPicks("duopicks-list", this);
		return lc;
	}
	
	private List<Pick> getCounters(String id, boolean fromAllPage)
	{
		List<Pick> lc = new ArrayList<Pick>();
		String url = getUrlTabPane(id);
		try {
			HTMLParser parser = null;
			if(url!=null)
			{
				parser = new HTMLParser(url);
			}
			else if(fromAllPage)
			{
				parser = this;
			}

			if(parser !=null)
			{
				lc=getPicks("counterpicks-list", parser);
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			LoLAutoCounterManager.getLogger().error(e.getCause());
		}
		return lc;
	}

	private List<Pick> getPicks(String picksType, HTMLParser htmlParser)
	{

		List<Pick> lc = new ArrayList<Pick>();
		//counterpicks-list
		Elements div = htmlParser.doc.select("div#"+picksType);
		Elements href =  div.select("a[href].picks-panel-link");
		int count=1;
		for(Element elt : href)
		{
			//LoLAutoCounterManager.getLogger().info(elt.attr("href"));
			String name = elt.attr("href");

			//Select div element placed after a element 
			//Element divInter = div.select("a[href="+name+"].picks-panel-link + div.picks-panel-interaction").first();
			Element divInter = elt.nextElementSibling();
			Element green = divInter.select("a.green").first();
			Element red = divInter.select("a.red").first();

			Float fgreenValue=0.0f;
			Float fredValue=0.0f;
			if(green!=null)
				fgreenValue=Float.valueOf(green.text());
			if(red!=null)
				fredValue=Float.valueOf(red.text());

			Float ratio=0.0f;
			if(fredValue>0)
			{
				ratio=fgreenValue/fredValue;
			}

			LoLAutoCounterManager.getLogger().info("  ->"+name+" : green="+fgreenValue+" ,red="+fredValue+" ,ratio="+ratio);
			Pick c = new Pick(new Champion(
					name),ratio);
			lc.add(c);


			count++;
			if(count > Constant.NUMBER_COUNTERS)
				break;
		}
		return lc;
	}
	
	
	public static void main(String argv[]) throws IOException {

		Document doc = Jsoup.parse(new File("D:\\PERSO\\html-src\\champinfo.html"), "UTF-8");

		//Champion list
		Elements scripts = doc.select("script");
		for(Element elt : scripts)
		{
			//LoLAutoCounterManager.getLogger().info(elt.toString());
			LoLAutoCounterManager.getLogger().info(elt.textNodes());
		}

		//Get general page
		Element a = doc.select("a[href=#General]").first();
		String ajaxRequest=a.attr("onClick");
		Pattern generalPattern  = Pattern.compile("ajaxLaneCounters\\('([0-9]*)', ([0-9]*)(.*?)");
		Matcher matcher1 = generalPattern.matcher(ajaxRequest);
		if(matcher1.find())
		{
			String champId = matcher1.group(1);
			String laneId = matcher1.group(2);

			LoLAutoCounterManager.getLogger().info("/../ajax/"+champId+"/lane/"+laneId);
		}
		
		//Get lane pages
		a = doc.select("a[href=#General]").first();
		ajaxRequest=a.attr("onClick");
		generalPattern  = Pattern.compile("ajaxLaneCounters\\('([0-9]*)', ([0-9]*)(.*?)");
		matcher1 = generalPattern.matcher(ajaxRequest);
		if(matcher1.find())
		{
			String champId = matcher1.group(1);
			String laneId = matcher1.group(2);

			LoLAutoCounterManager.getLogger().info("/../ajax/"+champId+"/lane/"+laneId);
		}
		
		//lanes
		Elements divLane = doc.select("div.champinfo_tag");
		for(Element div:divLane)
		{			
			Elements jungler = div.select("span.tag_jungler");
			if(!jungler.isEmpty())
			{
				LoLAutoCounterManager.getLogger().info("is jungler");
			}
			Elements top = div.select("span.tag_top");
			if(!top.isEmpty())
			{
				LoLAutoCounterManager.getLogger().info("is top");
			}

			Elements mid = div.select("span.tag_mid");
			if(!mid.isEmpty())
			{
				LoLAutoCounterManager.getLogger().info("is mid");
			}

		}
		//Get synergie
		Elements div = doc.select("div#duopicks-list");
		Elements href =  div.select("a[href].picks-panel-link");
		for(Element elt : href)
		{
			LoLAutoCounterManager.getLogger().info(elt.attr("href"));
			String name = elt.attr("href");

			//Select div element placed after a element 
			Element divInter = div.select("a[href="+name+"].picks-panel-link + div.picks-panel-interaction").first();
			LoLAutoCounterManager.getLogger().info(divInter.toString());
			Element green = divInter.select("a.green").first();
			Element red = divInter.select("a.red").first();
			
			LoLAutoCounterManager.getLogger().info(green.toString());
			LoLAutoCounterManager.getLogger().info(green.text());
			LoLAutoCounterManager.getLogger().info(red.text());
		}
	}
}
